/*
 * Description: 处理稳定性事件上报
 */
#include "event_reporter.h"
#include "log_event_handler.h"
#include "resource_event_handler.h"
#include "log.h"

namespace DFX {
const int EVENT_REPORT_INTERVAL_SECONDS = 300; // 打点上报间隔5min

void EventReporter::Init(std::shared_ptr<WINCONTROL::SendToHost> sendtoHost)
{
    if (sendtoHost == nullptr) {
        LOG_ERR("[DFX- Stability- EventReporter] - sendtoHost is null!");
        return;
    }
    m_sendtoHost = sendtoHost;
    Start();
}

void EventReporter::Deinit()
{
    Stop();
    if (m_sendtoHost != nullptr) {
        m_sendtoHost.reset();
    }
}
void EventReporter::Stop()
{
    LOG_INFO("[DFX - Stability] - EventReporter Stop");
    {
        std::lock_guard<std::mutex> lck(reportMtx);
        stopReportFlag = true;
    }
    reportCV.notify_one();
    if (eventReportThread.joinable()) {
        eventReportThread.join();
    }
}

void EventReporter::Start()
{
    LOG_INFO("[DFX - Stability] - EventReporter start");
    stopReportFlag = false;
    eventReportThread = thread([this]() { ReportEvent(); });
}

void EventReporter::ReportEvent()
{
    if (!LOG_EVENT_HANDLER.Init()) {
        LOG_ERR("[DFX - Stability] - LOG_EVENT_HANDLER init error");
        return;
    }

    if (!RES_EVENT_HANDLER.Init()) {
        LOG_ERR("[DFX - Stability] - RES_EVENT_HANDLER Init error");
        return;
    }

    // 处理事件日志里的事件
    LOG_EVENT_HANDLER.ReportOldEvents();
    LOG_EVENT_HANDLER.SubscribeEvents();
    std::unique_lock<std::mutex> lck(reportMtx);
    while (!stopReportFlag) {
        while (!reportCV.wait_for(lck, std::chrono::seconds(EVENT_REPORT_INTERVAL_SECONDS),
            [this]() { return (this == nullptr || stopReportFlag); })) {
            RES_EVENT_HANDLER.ReportResEvents();
        }
        LOG_INFO("[DFX - Stability] report loop break");
    }
    LOG_INFO("[DFX - Stability] - EventReporter Stop, start deinit");
    LOG_EVENT_HANDLER.DeInit();
    RES_EVENT_HANDLER.DeInit();
}

void EventReporter::ReportEventData(const string &eventName, const map<string, string> &eventData)
{
    LOG_INFO("[DFX - Stability] - start ReportEventData, EventName: {}, eventData.size:{}",
        eventName.c_str(), eventData.size());
    auto eventDataStr = StabilityCommon::MapToJson(eventData);
    LOG_INFO("[DFX - Stability] - m_sendtoHost send data: {}", eventDataStr.c_str());
}
}
